#include <iterator>
#include <cassert>
#include <nice2d/colorgradient.h>

ColorGradient::ColorGradient():
    colors()
{
}

sf::Color& ColorGradient::operator[] (float position)
{
	assert(position >= 0.f && position <= 1.f);
    return colors[position];
}

sf::Color ColorGradient::sampleColor(float position) const
{
    assert(colors.count(0.f) && colors.count(1.f));

    auto nextColor = colors.lower_bound(position);
	if (nextColor->first == position)
		return nextColor->second;

	auto prevColor = std::prev(nextColor);

	float interpolation = (position - prevColor->first) / (nextColor->first - prevColor->first);
	return blendColors(prevColor->second, nextColor->second, interpolation);
}

sf::Color blendColors(const sf::Color& firstColor, const sf::Color& secondColor, float interpolation)
{
	assert(interpolation >= 0.f && interpolation <= 1.f);

	float firstPart = 1.f - interpolation;

	return sf::Color(
		static_cast<sf::Uint8>(firstPart * firstColor.r + interpolation * secondColor.r),
		static_cast<sf::Uint8>(firstPart * firstColor.g + interpolation * secondColor.g),
		static_cast<sf::Uint8>(firstPart * firstColor.b + interpolation * secondColor.b),
		static_cast<sf::Uint8>(firstPart * firstColor.a + interpolation * secondColor.a));
}
